package com.shirley.myserialportapp

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shirley.serialportlib.SerialPortFinder
import com.shirley.serialportlib.SerialPortManager
import com.shirley.serialportlib.entity.Device
import com.shirley.serialportlib.listener.OnSerialPortOpenListener
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

class MainActivity : AppCompatActivity(), SerialPortDeviceAdapter.OnItemClickListener,
    OnSerialPortOpenListener {

    private val TAG = MainActivity::class.java.simpleName
    private var mSerialPortManager: SerialPortManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mSerialPortManager = SerialPortManager()
        mSerialPortManager?.setSerialPortOpenListener(this)

        recyclerView.layoutManager = LinearLayoutManager(this)
        val adapter = SerialPortDeviceAdapter(SerialPortFinder().devices)
        adapter.setOnItemClickListener(this)
        recyclerView.adapter = adapter
        recyclerView.addItemDecoration(DividerItemDecoration(this, RecyclerView.VERTICAL))
    }

    override fun onItemClick(device: Device) {
//        mSerialPortManager?.openSerialPort(device.file, 9600)
        val intent = Intent(this, SerialPortActivity::class.java)
        intent.putExtra("device", device)
        startActivity(intent)
    }

    override fun onSuccess(device: File?) {
        Toast.makeText(this, "打开串口成功", Toast.LENGTH_SHORT).show()
    }

    override fun onFail(device: File?, status: OnSerialPortOpenListener.Status?) {
        when (status) {
            OnSerialPortOpenListener.Status.WITHOUT_READ_WRITE_PERMISSION -> {
                showAlertDialog(device?.absolutePath, "没有读写权限")
            }
            OnSerialPortOpenListener.Status.OPEN_FAIL -> {
                showAlertDialog(device?.absolutePath, "串口打开失败")
            }
        }
    }

    /**
     * 展示警示弹框
     */
    private fun showAlertDialog(title: String?, message: String) {
        AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("Exit") { dialog, _ ->
                run { dialog.dismiss() }
            }
            .setCancelable(false)
            .create()
            .show()
    }

    override fun onDestroy() {
        super.onDestroy()
        mSerialPortManager?.let {
            mSerialPortManager?.closeSerialPort()
            mSerialPortManager = null
        }
    }

}
